package com.sdkj.dspservice.modules.report.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdkj.dspservice.common.base.controller.BaseController;
import com.sdkj.dspservice.common.config.ProjectConfig;
import com.sdkj.dspservice.common.react.AntdProResult;
import com.sdkj.dspservice.common.utils.CollectionsUtils;
import com.sdkj.dspservice.common.utils.DateUtils;
import com.sdkj.dspservice.common.utils.ExcelUtils;
import com.sdkj.dspservice.common.utils.StringUtils;
import com.sdkj.dspservice.modules.report.entity.Report;
import com.sdkj.dspservice.modules.report.entity.TableConfigColumn;
import com.sdkj.dspservice.modules.report.service.ReportService;
import com.sdkj.dspservice.modules.report.service.TableConfigColumnService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

/**
 * 报表控制器
 *
 * @author tm
 */
@Api(value = "报表", tags = "报表控制器")
@ApiResponses(@ApiResponse(code = 404, message = "报表不存在"))
@Slf4j
@Controller
@RequestMapping(value = "${project-config.apiUrl}/${project-config.version}/report/report")
public class ReportController extends BaseController {

    @Autowired
    private ReportService reportService;
    @Autowired
    private ProjectConfig projectConfig;
    @Autowired
    private TableConfigColumnService tableConfigColumnService;

    /**
     * 获取详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取详情")
    @GetMapping(value = "get")
    @ResponseBody
    public AntdProResult get(String id) {
        AntdProResult result = new AntdProResult();
        Report report = reportService.getById(id);
        result.success(report);
        return result;
    }

    /**
     * 获取列表
     *
     * @param report
     * @return
     */
    @ApiOperation(value = "获取列表")
    @GetMapping(value = "list")
    @ResponseBody
    public AntdProResult list(Report report) {
        AntdProResult result = new AntdProResult();
        List<Report> reportList = reportService.listLink(new QueryWrapper<>(report));
        result.success(reportList);
        return result;
    }

    /**
     * 保存（添加或修改）
     *
     * @param report
     * @return
     */
    @ApiOperation(value = "保存（添加或修改）")
    @PostMapping(value = "save")
    @ResponseBody
    public AntdProResult save(@Valid @RequestBody Report report) {
        AntdProResult result = new AntdProResult();
        reportService.saveOrUpdate(report);
        return result;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "remove")
    @ResponseBody
    public AntdProResult delete(String id) {
        AntdProResult result = new AntdProResult();
        reportService.removeById(id);
        return result;
    }

    /**
     * 获取select列表
     *
     * @param report
     * @return
     */
    @ApiOperation(value = "获取select列表")
    @GetMapping(value = "listForSelect")
    @ResponseBody
    public AntdProResult listForSelect(Report report) {
        AntdProResult result = new AntdProResult();
        List<Report> reportList = reportService.list(report);
        // 转换为{label:xxx,value:xxx}
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Report r : reportList) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("label", r.getName());
            map.put("value", r.getId());
            mapList.add(map);
        }
        result.success(mapList);
        return result;
    }

    /**
     * sql执行
     *
     * @param paramMap
     * @return
     */
    @ApiOperation(value = "sql执行")
    @PostMapping(value = "executeSql")
    @ResponseBody
    public AntdProResult executeSql(@RequestBody Map<String, Object> paramMap) throws SQLException {
        return reportService.executeSql(paramMap);
    }

    /**
     * 查看次数增加
     *
     * @return
     */
    @ApiOperation(value = "查看次数增加")
    @RequestMapping(value = "addSeeNumber")
    @ResponseBody
    public AntdProResult addSeeNumber(String id) throws SQLException {
        AntdProResult result = new AntdProResult();
        Report report = reportService.getById(id);
        report.setSeeNumber(report.getSeeNumber() + 1);
        reportService.saveOrUpdate(report);
        result.success("");
        return result;
    }

    /**
     * 导出
     *
     * @return
     */
    @ApiOperation(value = "导出")
    @RequestMapping(value = "export")
    public void export(HttpServletResponse response, HttpServletRequest request) throws SQLException, IOException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> paramMap = new HashMap<>();
        for (String key : parameterMap.keySet()) {
            String value = parameterMap.get(key)[0];
            if (value.indexOf(",") != -1) {
                List<String> valueList = new ArrayList<>();
                valueList.addAll(Arrays.asList(value.split(",")));
                paramMap.put(key, valueList);
            } else {
                paramMap.put(key, value);
            }
        }
        paramMap.put("current", 1);
        paramMap.put("pageSize", 999999999);
        // 去除reportId
        String reportId = String.valueOf(paramMap.get("reportId"));
        paramMap.remove("reportId");
        // 查询该报表
        Report report = reportService.getById(reportId);
        String reportName = report != null ? report.getName() : "test";
        // 执行sql
        AntdProResult result = reportService.executeSql(paramMap);
        Map<String, List<List<Object>>> map = new HashMap<>();
        List<List<Object>> data = new ArrayList<>();
        // 添加标题
        List<Object> titleList = new ArrayList<>();
        // 添加筛选参数
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("table_config_id", String.valueOf(paramMap.get("tableConfigId")));
        queryWrapper.eq("is_show", "1");
        queryWrapper.orderByAsc("sort");
        List<TableConfigColumn> tableConfigColumnList = tableConfigColumnService.list(queryWrapper);
        if (CollectionsUtils.isNotEmpty(tableConfigColumnList)) {
            for (TableConfigColumn tableConfigColumn : tableConfigColumnList) {
                titleList.add(StringUtils.isNotBlank(tableConfigColumn.getComment()) ? tableConfigColumn.getComment() : tableConfigColumn.getColumnName());
            }
            data.add(titleList);
        }
        // 组装数据
        for (Map<String, Object> resultData : (List<Map<String, Object>>) result.getData()) {
            List<Object> resultDataList = new ArrayList<>();
            for (Object key : resultData.keySet()) {
                System.out.println(key);
                System.out.println(resultData.get(key));
                resultDataList.add(String.valueOf(resultData.get(key)));

            }
            data.add(resultDataList);
        }

        map.put("Sheet1", data);
        System.out.println(map.toString());
        ExcelUtils excelUtils = new ExcelUtils(1, map, true);
        excelUtils.write(response, reportName + DateUtils.getDate("yyyyMMdd") + ".xls");
    }

}
